// FormDesign
import adminApi from '@/services/adminApi';
import { EditOutlined, ReloadOutlined, SortAscendingOutlined } from '@ant-design/icons';
import type { ActionType } from '@ant-design/pro-components';
import { DragSortTable, EditableProTable, ProCard, ProTable } from '@ant-design/pro-components';
import { Button, Popconfirm, Space, Table } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
const TableDesign: React.FC<{ modId: number }> = (props) => {
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [tableTypes, setTableTypes] = useState<any>(1);
  const [sortDataSource, setSortDatasource] = useState<any>([]);
  const [demoColumns, setDemoColumns] = useState<any>([]);
  const leftRef = useRef<ActionType>();
  const rightRef = useRef<ActionType>();
  const leftcolumns: any[] = [
    {
      title: '字段标题',
      dataIndex: 'title',
      ellipsis: 'true',
    },
    {
      title: '字段名',
      dataIndex: 'name',
      search: false,
    },
    {
      title: '操作',
      width: 60,
      key: 'option',
      valueType: 'option',
      render: (_: any, record: any, _index: any, action: { reload: () => void }) => [
        <a
          key="formattradd"
          onClick={async () => {
            await adminApi.cms.AdminapiCmsTableattradd({
              attr_id: record.id,
              mod_id: props.modId,
              alias: record.title,
            });
            action?.reload();
            rightRef?.current?.reload();
          }}
        >
          添加
        </a>,
      ],
    },
  ];
  const rightcolumns: any[] = [
    {
      title: '标题别名',
      dataIndex: 'alias',
      tooltip: '表单展示的标题,如果不修改默认字段原标题',
      // formItemProps: (form, { rowIndex }) => {
      //   return {
      //     rules: rowIndex > 1 ? [{ required: true, message: '此项为必填项' }] : [],
      //   };
      // },
      // // 第一行不允许编辑
      // editable: (text, record, index) => {
      //   return index !== 0;
      // },
    },
    {
      title: '字段名',
      dataIndex: ['cms_attr', 'name'],
      tooltip: '只读，使用form.getFieldValue可以获取到值',
      readonly: true,
    },
    {
      title: '自动缩略',
      dataIndex: 'ellipsis',
      tooltip: '是否自动缩略',
      valueType: 'select',
      request: async () => [
        {
          value: true,
          label: '是',
        },
        {
          value: false,
          label: '否',
        },
      ],
    },
    {
      title: '支持复制',
      dataIndex: 'copyable',
      tooltip: '是否支持复制',
      valueType: 'select',
      request: async () => [
        {
          value: true,
          label: '是',
        },
        {
          value: false,
          label: '否',
        },
      ],
    },
    {
      title: '是否搜索',
      dataIndex: 'search',
      tooltip: '配置列的搜索相关，false 为隐藏',
      valueType: 'select',
      request: async () => [
        {
          value: true,
          label: '是',
        },
        {
          value: false,
          label: '否',
        },
      ],
    },
    {
      title: '支持排序',
      dataIndex: 'sorter',
      tooltip: '是否支持排序',
      valueType: 'select',
      request: async () => [
        {
          value: true,
          label: '是',
        },
        {
          value: false,
          label: '否',
        },
      ],
    },
    {
      title: '操作',
      valueType: 'option',
      width: 120,
      fixed: 'right',
      render: (text: any, record: { id: any }, _: any, action: any) => [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.id);
          }}
        >
          编辑
        </a>,
        <Popconfirm
          key="delete"
          title={`确认删除吗?`}
          okText="是"
          cancelText="否"
          onConfirm={async () => {
            await adminApi.cms.AdminapiCmsTableattrdel({
              id: record.id,
            });
            action?.reload();
            leftRef?.current?.reload();
          }}
        >
          <a>删除</a>
        </Popconfirm>,
      ],
    },
  ];
  const sortColumns: any[] = [
    {
      title: '排序',
      dataIndex: 'sort',
      width: 60,
    },
    {
      title: '标题别名',
      dataIndex: 'alias',
      tooltip: '表单展示的标题,如果不修改默认字段原标题',
      // formItemProps: (form, { rowIndex }) => {
      //   return {
      //     rules: rowIndex > 1 ? [{ required: true, message: '此项为必填项' }] : [],
      //   };
      // },
      // // 第一行不允许编辑
      // editable: (text, record, index) => {
      //   return index !== 0;
      // },
    },
    {
      title: '字段名',
      dataIndex: 'a_name',
      tooltip: '只读，使用form.getFieldValue可以获取到值',
    },
    {
      title: '自动缩略',
      dataIndex: 'ellipsis',
      tooltip: '是否自动缩略',
      valueType: 'select',
      request: async () => [
        {
          value: true,
          label: '是',
        },
        {
          value: false,
          label: '否',
        },
      ],
    },
    {
      title: '支持复制',
      dataIndex: 'copyable',
      tooltip: '是否支持复制',
      valueType: 'select',
      request: async () => [
        {
          value: true,
          label: '是',
        },
        {
          value: false,
          label: '否',
        },
      ],
    },
    {
      title: '是否搜索',
      dataIndex: 'search',
      tooltip: '配置列的搜索相关，false 为隐藏',
      valueType: 'select',
      request: async () => [
        {
          value: true,
          label: '是',
        },
        {
          value: false,
          label: '否',
        },
      ],
    },
    {
      title: '支持排序',
      dataIndex: 'sorter',
      tooltip: '是否支持排序',
      valueType: 'select',
      request: async () => [
        {
          value: true,
          label: '是',
        },
        {
          value: false,
          label: '否',
        },
      ],
    },
  ];
  const tableColumns = async () => {
    const res: any = await adminApi.cms.AdminapiCmsTableschema({ mod_id: props.modId });
    const modInfo = res.data.modInfo;
    const list = res.data.list;
    console.log(modInfo, list);
    const carr: any[] = [];
    for (const v of list) {
      const cobj: any = {};
      console.log(v);
      cobj.title = v.alias || v.cms_attr.title;
      cobj.dataIndex =
        v.cms_attr.mod_id !== 1 ? [modInfo.tableName, v.cms_attr.name] : v.cms_attr.name;
      carr.push(cobj);
    }
    setDemoColumns(carr);
  };
  useEffect(() => {
    tableColumns();
  }, [sortDataSource]);
  const handleDragSortEnd = async (newDataSource: any) => {
    // console.log('排序后的数据', newDataSource);
    setSortDatasource(newDataSource);
    await adminApi.cms.AdminapiCmsTablesort({}, newDataSource);
    // message.success('修改列表排序成功');
  };
  return (
    <>
      <ProCard split="vertical" gutter={16} bodyStyle={{ paddingLeft: 8, paddingRight: 8 }}>
        <ProCard ghost>
          <ProTable
            ghost
            actionRef={leftRef}
            columns={leftcolumns}
            rowSelection={{
              // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
              // 注释该行则默认不显示下拉选项
              selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
              defaultSelectedRowKeys: [],
            }}
            tableAlertRender={({ selectedRowKeys, onCleanSelected }) => (
              <Space size={24}>
                <span>
                  已选 {selectedRowKeys.length} 项
                  <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                    取消选择
                  </a>
                </span>
              </Space>
            )}
            tableAlertOptionRender={() => {
              return (
                <Space size={16}>
                  <a>批量添加</a>
                </Space>
              );
            }}
            request={async (params: any = {}, sort, filter): Promise<any> => {
              console.log(sort, filter);
              return await adminApi.cms.AdminapiCmsTalbeattrlist(params);
            }}
            params={{ mod_id: props.modId }}
            options={false}
            search={false}
            rowKey="id"
            headerTitle="可用字段"
            pagination={false}
            toolBarRender={() => [
              <Button
                key="shuaxin"
                type="dashed"
                shape="circle"
                icon={<ReloadOutlined />}
                onClick={() => leftRef?.current?.reload()}
              />,
            ]}
          />
        </ProCard>
        <ProCard colSpan={17} ghost>
          {tableTypes === 1 ? (
            <EditableProTable
              ghost
              actionRef={rightRef}
              rowKey="id"
              headerTitle="编辑表单"
              scroll={{
                x: 960,
              }}
              recordCreatorProps={false}
              loading={false}
              columns={rightcolumns}
              request={async (params: any): Promise<any> => {
                const res = await adminApi.cms.AdminapiCmsTableattrselect(params);
                setSortDatasource(res.data);
                return res;
              }}
              params={{ mod_id: props.modId }}
              value={dataSource}
              onChange={setDataSource}
              toolBarRender={() => [
                <Button
                  key="sortarrt"
                  icon={<SortAscendingOutlined />}
                  onClick={() => setTableTypes(2)}
                >
                  字段排序
                </Button>,
              ]}
              editable={{
                type: 'multiple',
                editableKeys,
                onSave: async (rowKey, data, row) => {
                  console.log(rowKey, data, row);
                  await adminApi.cms.AdminapiCmsTableattredit({}, data);
                  rightRef?.current?.reload();
                },
                onChange: setEditableRowKeys,
              }}
            />
          ) : (
            <DragSortTable
              ghost
              headerTitle="表单排序"
              columns={sortColumns}
              rowKey="id"
              pagination={false}
              dataSource={sortDataSource}
              dragSortKey="sort"
              onDragSortEnd={handleDragSortEnd}
              search={false}
              options={false}
              toolBarRender={() => [
                <Button key="editarrt" icon={<EditOutlined />} onClick={() => setTableTypes(1)}>
                  编辑字段
                </Button>,
              ]}
            />
          )}
        </ProCard>
      </ProCard>
      <ProCard
        title="表格预览"
        headerBordered
        collapsible
        defaultCollapsed
        onCollapse={(collapse) => console.log(collapse)}
        extra={
          <Button
            size="small"
            onClick={(e) => {
              e.stopPropagation();
            }}
          >
            提交
          </Button>
        }
        type="inner"
        size="small"
        style={{ marginTop: 16 }}
      >
        <ProTable
          columns={demoColumns}
          rowSelection={{
            // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
            // 注释该行则默认不显示下拉选项
            selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
            defaultSelectedRowKeys: [],
          }}
          tableAlertRender={({ selectedRowKeys, onCleanSelected }) => (
            <Space size={24}>
              <span>
                已选 {selectedRowKeys.length} 项
                <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                  取消选择
                </a>
              </span>
            </Space>
          )}
          tableAlertOptionRender={() => {
            return (
              <Space size={16}>
                <a>批量删除</a>
                <a>导出数据</a>
              </Space>
            );
          }}
          dataSource={[]}
          scroll={{ x: 1300 }}
          rowKey="key"
          headerTitle="批量操作"
        />
      </ProCard>
    </>
  );
};

export default TableDesign;
